package userlogin.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import userlogin.Entity.Dto.Code;
import userlogin.Entity.UserId;
import userlogin.Mapper.UserIdMapper;
import userlogin.Service.UserIdService;
import userlogin.Util.ApiResult;
import userlogin.Util.TimeUtils;

import java.util.HashMap;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 小陈同学
 * @since 2023-06-25
 */
@Service
public class UserIdServiceImpl extends ServiceImpl<UserIdMapper, UserId> implements UserIdService {

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;
    @Autowired
    private UserIdMapper userIdMapper;
    @Autowired
    private UserIdService userIdService;

    @Autowired
    private RestTemplate restTemplate;

    public String getOpenId(String js_code) {
        /*小程序用户登录
         * 1. 从小程序端获取code
         * 2. 根据url 进行一一对应替换
         * 3. 由于小程序端传来的数据为一段字符型的数据
         * 3. 使用JSON格式对小程序端的数据进行转换
         * 4. 获得openid
         * */
        RestTemplate client = new RestTemplate();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type=authorization_code";
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", js_code);
        try {
            ResponseEntity response = client.getForEntity(url, String.class, map);
            String data = (String) response.getBody();
            HashMap<String, String> dataMap = JSON.parseObject(data, HashMap.class);
            String openid = dataMap.get("openid");
            return openid;
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }
    }

    @Override
    public String login(Code c) {
        System.out.println("输出:" + c.getCode());
        String code = c.getCode();
        if (code == null)
            return ApiResult.args();
        try {
            String openid = userIdService.getOpenId(code);
            UserId userId = userIdMapper.getUserInfo(openid);
            if (userId == null) {
                String time = TimeUtils.getNowDateTime();
                userIdMapper.insertUserInfo(openid, time);
                UserId user = new UserId();
                user.setOpenid(openid);
                return ApiResult.ok(user);
            } else {
                String time = TimeUtils.getNowDateTime();
                userIdMapper.updateLogin(openid, time);
                return ApiResult.ok(userId);
            }
        } catch (Exception e) {
            log.error(e.toString());
            return ApiResult.error();
        }
    }

    @Override
    public UserId getUserInfo(String openid) {
        return userIdMapper.findById(openid);
    }

}
